import { useState, useEffect } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import { Card, Form, Input, Button, Radio, Upload, Select, Breadcrumb, message } from "antd"
import { Link } from 'react-router-dom'
import ReactQuill from "react-quill";
import { useSearchParams } from 'react-router-dom';



// 引入富文本编辑器的样式文件
import 'react-quill/dist/quill.snow.css';
import './index.scss'

import { useChannel } from '@/hooks/useChannel'
import { createArticleAPI, getArticleAPI, updateArticleAPI } from '@/apis'

const Publish = () => {
	// 路由参数
	const [searchParams] = useSearchParams()
	const articleId = searchParams.get('id')

	// 表单数据
	const [form] = Form.useForm()

	// 获取文章详情
	useEffect(() => {
		// 如果有文章id，则从服务器获取文章详情
		if (articleId) {
			(async () => {
				const data = await getArticleAPI(articleId).then(res =>
					res.data
				);
				form.setFieldsValue({
					...data,
					type: data.cover.type
				})
				setImageType(data.cover.type)
				setImageList(data.cover.images.map(url => ({
					url
				})))
			})()
		}
	}, [articleId, form])

	// 获取频道列表
	const { channelList } = useChannel()

	// 表单提交的回调函数
	const onFinish = (formValue) => {
		if (imageList.length !== imageType) {
			message.error('请上传正确数量的图片！')
			return
		}

		// 组装表单数据
		const { title, content, channel_id, type } = formValue
		const formData = {
			title,
			content,
			channel_id,
			cover: {
				type, 
				// 上传图片的url数组
				images: imageList.map(item => {
					if (item.response) {
						return item.response.data.url
					} else {
						return item.url
					}
				})
			}
		}

		if (articleId) updateArticleAPI(articleId,formData)
		else createArticleAPI(formData)

		message.success('文章发布成功！')
	}

	// 图片上传列表
	const [imageList, setImageList] = useState([])
	// 上传图片的回调函数
	const onUploadChange = (value) => {
		setImageList(value.fileList)
	}

	// 图片类型
	const [imageType, setImageType] = useState(0)
	// 图片类型选择的回调函数
	const onTypeChange = (e) => {
		setImageType(e.target.value)
	}

	return (
		<div className='publish-container '>
			<Card title={
				<Breadcrumb items={[
					{ title: <Link to={'/'}> 首页 </Link> },
					{ title: `${articleId ? '编辑' : '发布'}文章` }
				]} />
			} bordered={false}>
				<Form
					layout="horizontal"
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 16 }}
					initialValues={{ type: 0 }}
					form={form}
					onFinish={onFinish}
				>
					<Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入文章标题!' }]}>
						<Input placeholder='请输入文章标题' />
					</Form.Item>

					<Form.Item label="频道" name="channel_id" rules={[{ required: true, message: '请输入文章频道!' }]}>
						<Select placeholder="请输入文章频道">
							{
								channelList.map((item) => <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
								)
							}
						</Select>
					</Form.Item>
					<Form.Item label="封面">
						<Form.Item name="type" rules={[{ required: true, message: 'Please select!' }]}>
							<Radio.Group onChange={onTypeChange}>
								<Radio value={1}>单图</Radio>
								<Radio value={3}>三图</Radio>
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						{
							imageType > 0 && <Upload
								name="image"
								listType="picture-card"
								showUploadList
								action={'https://geek.itheima.net/v1_0/upload'}
								onChange={onUploadChange}
								maxCount={imageType}
								fileList={imageList}
							>
								<PlusOutlined />
							</Upload>
						}
					</Form.Item>
					<Form.Item
						label="内容"
						name="content"
						rules={[{ required: true, message: '请输入文章内容!' }]}>
						<ReactQuill
							theme="snow"
							className="publish-quill"
							placeholder='请输入文章内容' />
					</Form.Item>
					<Form.Item wrapperCol={{ offset: 4 }}>
						<Button type="primary" htmlType="submit">{articleId ? '编辑' : '发布'}文章</Button>
					</Form.Item>
				</Form>
			</Card>
		</div >
	)
}

export default Publish